package mail.client.pkg1142076;

import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.JOptionPane;

/**
 *
 * @author Quân
 */
public class MailClientManager {

    private static MailClientManager instance = null;
    Store store = null;
    private String userName;
    private String password;
    private String sendingHost = "smtp.gmail.com";
    private int sendingPort = 465;
    private String from;
    private String to;
    private String subject;
    private String content;
    private String receivingHost;
//    private int receivingPort;
    private Properties properties;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSendingHost() {
        return sendingHost;
    }

    public void setSendingHost(String sendingHost) {
        this.sendingHost = sendingHost;
    }

    public int getSendingPort() {
        return sendingPort;
    }

    public void setSendingPort(int sendingPort) {
        this.sendingPort = sendingPort;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getReceivingHost() {
        return receivingHost;
    }

    public void setReceivingHost(String receivingHost) {
        this.receivingHost = receivingHost;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public Store connect() {
        Properties props = System.getProperties();
        props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.pop3.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props, null);
        try {
            store = session.getStore(properties.getProperty("Protocol"));
            store.connect(
                    properties.getProperty("IncomingHost"),
                    properties.getProperty("Email"),
                    properties.getProperty("Password"));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return store;
    }

    public static MailClientManager getInstance() {
        if (instance == null) {
            instance = new MailClientManager();
        }
        return instance;
    }

    public List<Object[]> getMail() {
        List<Object[]> list = new ArrayList<>();
        if (store == null) {
            connect();
        }
        Folder folder;
        try {
            folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.getMessages();

            // Retrieve message headers for each message in folder.
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            folder.fetch(messages, profile);

            for (int i = 0; i < messages.length; i++) {
                StringBuilder emailFrom = new StringBuilder();
                InternetAddress address[] = (InternetAddress[]) messages[i].getFrom();
                for (int j = 0; j < address.length; j++) {
                    if (j != 0) {
                        emailFrom.append(", ");
                    }
                    String personal = address[j].getPersonal();
                    if (!personal.isEmpty()) {
                        emailFrom.append(address[j].getPersonal());
                    } else {
                        emailFrom.append(address[j].getAddress());
                    }
                }
                list.add(new Object[]{
                            new MyMessage(messages[i]),
                            emailFrom.toString()
                        });
            }
        } catch (MessagingException ex) {
            Logger.getLogger(MailClientManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return list;
    }

    public void sendMail(String to, String subject, String content) {

        Properties props = new Properties();
        props.put("mail.smtp.host", properties.getProperty("OutComingHost"));
        props.put("mail.smtp.user", properties.getProperty("Email"));
        props.put("mail.smtp.password", properties.getProperty("Password"));
        props.put("mail.smtp.auth", "true");
        Session session1 = Session.getDefaultInstance(props);

        //MIME stands for Multipurpose Internet Mail Extensions

        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;

        try {
            fromAddress = new InternetAddress(properties.getProperty("Email"));
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            String mes = "Sending email to: " + to + " failed !!!";
            JOptionPane.showMessageDialog(null, mes, "Falied to Send!!!",
                    JOptionPane.ERROR_MESSAGE);
        }

        Message simpleMessage = new MimeMessage(session1);
        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(content);

            Transport transport = session1.getTransport("smtps");
            transport.connect(properties.getProperty("OutComingHost"),
                    properties.getProperty("Email"),
                    properties.getProperty("Password"));
            transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
            transport.close();
            JOptionPane.showMessageDialog(
                    null, "Mail sent successfully ...", "Mail sent",
                    JOptionPane.PLAIN_MESSAGE);
        } catch (MessagingException e) {
            JOptionPane.showMessageDialog(
                    null, "Sending email to: " + to + " failed !!!",
                    "Falied to Send!!!", JOptionPane.ERROR_MESSAGE);
        }
    }
}
